//
//  OpenSDK_LoginLoadingView.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/20.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_LoginLoadingView.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_UIManager.h"
#import "OpenSDK_UIUtil.h"

@interface OpenSDK_LoginLoadingView ()

@end

@implementation OpenSDK_LoginLoadingView

{
    OpenSDK_AccountRecord *loginAccount;
    NSTimeInterval startTime;
    NSTimeInterval realnameStartTime;
    BOOL cancelLogin;
}

static NSTimeInterval MIN_LOGIN_DURATION = 2;//最小登录等待时长,单位:秒
static NSTimeInterval MIN_REALNAME_DURATION = 1.5;//最小实名认证等待时长,单位:秒

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 10;
    _bgView.layer.masksToBounds = true;
    // Do any additional setup after loading the view.
    
//    [self.bgView.layer setCornerRadius:3.0];
//
//    [self.switchAccountBtn.layer setCornerRadius:3.0];
//    [self.switchAccountBtn.layer setBorderWidth:1.0];
//    [self.switchAccountBtn.layer setBorderColor:[UIColor blueColor].CGColor];
    if (self.isHideSwitchAccount) {
        self.switchAccountBtn.hidden = YES;
    }
    
    self.loadingMsgView.text = [NSString stringWithFormat:@"%@，%@", self.accoutnName, @"登录中..."];
    
    // loadingIcon一直旋转
    CABasicAnimation *layerAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    layerAnimation.toValue = @(2*M_PI);
    layerAnimation.duration = 0.5;//旋转速度
    layerAnimation.removedOnCompletion = false;
    layerAnimation.repeatCount = MAXFLOAT;
    [self.loadingIconView.layer addAnimation:layerAnimation forKey:nil];
    
    // 记录登录操作开始时间
    startTime = [[NSDate date] timeIntervalSince1970];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    //bgView的最终位置 当前窗口的大小
    CGRect finalFrame = self.bgView.frame;
    //bgView的初始位置 在屏幕上方
    self.bgView.frame = CGRectOffset(finalFrame, 0, -100);
    //执行动画
    [UIView animateWithDuration:0.5
                     animations:^{
        self.bgView.frame = finalFrame;
    } completion:nil];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - login result

//登录结果回调
- (void)loginResultCallback:(BOOL) result account:(OpenSDK_AccountRecord *)account {
    [self loginResultCallback:result account:account delegate:nil];
}

//登录结果回调(带delegate,登录失败，关闭界面，会回调delegate)
- (void)loginResultCallback:(BOOL) result account:(OpenSDK_AccountRecord *)account delegate:(void (^ __nullable)(void))delegate {
    if (cancelLogin) {
        NSLog(@"中途取消登录，切换账号");
        return;
    }
    if (!result) {
        //返回的上一个VC
        NSLog(@"登录失败，返回上一个界面");
        [self closeView:YES delegate:delegate];
        return;
    }
    if (account == nil) {
        return;
    }
    loginAccount = account;
    self.loginSuccessView.text = [NSString stringWithFormat:@"%@，%@", account.accountName, @"登录成功!"];
    NSTimeInterval endTime = [[NSDate date] timeIntervalSince1970];
    if (endTime - startTime < MIN_LOGIN_DURATION) {
        NSTimeInterval extraTime = MIN_LOGIN_DURATION - (endTime - startTime);
        NSLog(@"登录成功，还需额外等待%f秒", extraTime);
        [NSTimer scheduledTimerWithTimeInterval:extraTime
                                         target:self
                                       selector:@selector(showSuccess)
                                       userInfo:nil
                                        repeats:NO];
    } else {
        NSLog(@"登录成功，无需额外等待");
        [self showSuccess];
    }
}

#pragma mark - 动画结束回调函数：展示登录成功loading
- (void)showSuccess {
    if (cancelLogin) {
        NSLog(@"中途取消登录，切换账号");
        return;
    }
    if (loginAccount == nil) {
        NSLog(@"account为空，取消登录");
        return;
    }
    self.loadingIconView.hidden = YES;
    self.loadingMsgView.hidden = YES;
    self.switchAccountBtn.hidden = YES;
    self.loginSuccessView.hidden = NO;
    
    // 支付跳转过来的，不进行实名认证的逻辑，不回调登录成功，直接调起支付
    if (self.order) {
        NSLog(@"%f秒后登录成功,然后调起支付", MIN_REALNAME_DURATION);
        // 不需要实名认证，MIN_REALNAME_DURATION秒后自动关闭
        [NSTimer scheduledTimerWithTimeInterval:MIN_REALNAME_DURATION
                                         target:self
                                       selector:@selector(closeLoadingWithPay)
                                       userInfo:nil
                                        repeats:NO];
        return;
    }
    // 登录跳转过来的，如果需要绑定手机或实名认证，则查询该用户是否已经实名认证
    if ([OpenSDK_DataManager getInstance].isAppstoreReview){
        [NSTimer scheduledTimerWithTimeInterval:MIN_REALNAME_DURATION
                                         target:self
                                       selector:@selector(closeLoadingWithLoginSuccess)
                                       userInfo:nil
                                        repeats:NO];
    }else{
        if ((loginAccount.needMobile != 0) && !loginAccount.isMobile) {
            // 弹出绑定手机框
            UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
            UIViewController *vc = (UIViewController *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_BindMobileView"];
            [self closeView:NO delegate:^{
                self.bgView.hidden = YES;
            }];
            [self.navigationController pushViewController:vc animated:NO];
        } else if ((loginAccount.needReal != 0) && !loginAccount.isReal) {
            NSLog(@"需要实名认证");
            // 弹出实名认证框
            UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
            UIViewController *vc = (UIViewController *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_RealNameView"];
            [self closeView:NO delegate:^{
                self.bgView.hidden = YES;
            }];
            [self.navigationController pushViewController:vc animated:NO];
        } else {
            NSLog(@"实名认证关闭,%f秒后登录成功", MIN_REALNAME_DURATION);
            // 不需要实名认证，MIN_REALNAME_DURATION秒后自动关闭
            [NSTimer scheduledTimerWithTimeInterval:MIN_REALNAME_DURATION
                                             target:self
                                           selector:@selector(closeLoadingWithLoginSuccess)
                                           userInfo:nil
                                            repeats:NO];
        }
    }
    
}

#pragma mark - 动画结束回调函数：关闭loading，回调登录成功
- (void)closeLoadingWithLoginSuccess {
    [self closeView:NO delegate:^{
        [[OpenSDK_UIManager getInstance] closeUI];
        // 发送登录成功事件
        [[OpenSDK_LoginManager getInstance] sendLoginSuccessEvent];
    }];
}

#pragma mark - 动画结束回调函数：关闭loading，回调支付成功
- (void)closeLoadingWithPay {
    [self closeView:NO delegate:^{
        [[OpenSDK_UIManager getInstance] closeUI];
        [[OpenSDK_UIManager getInstance] showPayUI:self.order];
    }];
}

#pragma mark - 关闭loading的动画
- (void)closeView:(BOOL)dismiss delegate:(void (^ __nullable)(void))delegate {
    //bgView的最终位置，在屏幕上方
    CGRect finalFrame = CGRectOffset(self.bgView.frame, 0, -100);
    //执行动画，从当前位置，退到屏幕上方
    [UIView animateWithDuration:0.5
                     animations:^{
        self.bgView.frame = finalFrame;
    } completion:^(BOOL finished) {
        if (dismiss) {
            [self.navigationController popViewControllerAnimated:NO];
        }
        if (delegate) {
            delegate();
        }
    }];
}

#pragma mark - btn delegate
- (IBAction)didClickSwitchAccountBtn:(id)sender {
    cancelLogin = YES;
    // 关闭loading框
    [self closeView:YES delegate:^{
        NSLog(@"登录失败，返回登录首页");
        // 切换账号，返回登录页面
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
        UIViewController *vc;
        if ([[OpenSDK_DataManager getInstance] getCurAccount] == nil) {
            // 没有历史账号，则跳转到手机登录界面
            vc = (UIViewController *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginMobileView"];
        } else {
            // 有历史账号，跳转到快捷登录界面
            vc = (UIViewController *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_QuickLoginView"];
        }
        [self.navigationController pushViewController:vc animated:NO];
    }];
}

@end
